package com.jike.noobmoney.mvp.view.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.image.imagepicker.ImagePicker;
import com.image.imagepicker.bean.ImageItem;
import com.image.imagepicker.ui.ImageGridActivity;
import com.image.imagepicker.ui.ImagePreviewDelActivity;
import com.jike.noobmoney.R;
import com.jike.noobmoney.adapter.ImagePickerAdapter;
import com.jike.noobmoney.contants.ConstantValue;
import com.jike.noobmoney.entity.UploadFilesEntity;
import com.jike.noobmoney.helper.ImageLoader;
import com.jike.noobmoney.mvp.presenter.AppPresenter;
import com.jike.noobmoney.mvp.presenter.UserPresenter;
import com.jike.noobmoney.net.IView;
import com.jike.noobmoney.util.ComUtils;
import com.jike.noobmoney.util.Logger;
import com.jike.noobmoney.util.SPUtils;
import com.jike.noobmoney.util.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.iwf.photopicker.PhotoPreview;

public class GuanzhuActivity extends BaseActivity implements IView, ImagePickerAdapter.OnRecyclerViewItemClickListener {


    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.tv_submit)
    TextView tvSubmit;
    @BindView(R.id.tv_tip)
    TextView tvTip;
    @BindView(R.id.tv_jinqun)
    TextView tvJinqun;
    @BindView(R.id.ll_info)
    LinearLayout llInfo;
    @BindView(R.id.iv_ecode)
    ImageView icCode;
    private int flag = 1;
    private AppPresenter appPresenter;
    public static final int IMAGE_ITEM_ADD = -1;
    private int maxImgCount = 9;               //允许选择图片最大数
    private ArrayList<ImageItem> selImageList; //当前选择的所有图片
    public static final int REQUEST_CODE_PREVIEW = 101;
    public static final int REQUEST_CODE_SELECT = 100;
    private ImagePickerAdapter adapter;
    private UserPresenter userPresenter;
    private String userid;

    public static void startAct(Context context, int flag) {
        Intent intent = new Intent(context, GuanzhuActivity.class);
        intent.putExtra("flag", flag);
        context.startActivity(intent);
    }

    @Override
    protected int layoutResID() {
        return R.layout.activity_guanzhu;
    }

    @Override
    protected void initData() {
        flag = getIntent().getIntExtra("flag", 1);
        appPresenter = new AppPresenter(this);    //上传图片
        userPresenter = new UserPresenter(this);

        if (flag == 2) {
            llInfo.setVisibility(View.VISIBLE);
            tvTitle.setText("新手任务");
            tvJinqun.setVisibility(View.VISIBLE);
            tvTip.setText("QQ搜索群:564104407 并加入,然后截图提交审核");
        } else if (flag == 3) {
            llInfo.setVisibility(View.GONE);
            tvTitle.setText("关注公众号");
            tvJinqun.setVisibility(View.GONE);
            tvTip.setText("微信搜索公众号:小白赚钱(微信号:xbzqapp)");
        } else {
            llInfo.setVisibility(View.VISIBLE);
            tvTitle.setText("新手任务");
            tvJinqun.setVisibility(View.GONE);
            tvTip.setText("微信搜索公众号:小白赚钱(微信号:xbzqapp) 并关注,然后截图提交审核");
        }

        selImageList = new ArrayList<>();
        adapter = new ImagePickerAdapter(this, selImageList, maxImgCount);
        adapter.setOnItemClickListener(this);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);

        ImageLoader.displayImage(this, ConstantValue.WXURL, icCode);
        icCode.setOnClickListener(v -> {
            String url = ConstantValue.WXURL;
            ArrayList<String> photoPaths = new ArrayList<>();
            photoPaths.add(url);
            PhotoPreview.builder()
                    .setPhotos(photoPaths)
                    .setCurrentItem(0)
                    .setShowDeleteButton(true)
                    .start((Activity) context);
        });
    }

    @OnClick({R.id.iv_back, R.id.tv_submit, R.id.tv_jinqun})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_submit:
                uploadFiles();
                break;
            case R.id.tv_jinqun:
                ComUtils.startQQ(context, 3, "564104407");
                break;
        }
    }

    /**
     * 提交任务
     */
    public void submitOrder(String url) {
        showProgress();
        userid = SPUtils.getInstance().getString(ConstantValue.SpType.userid);
        userPresenter.newusertaskimage(userid, "" + flag, url, ConstantValue.RequestKey.new_task_tijiao);
    }

    /**
     * 上传图片
     */
    private void uploadFiles() {
        showProgress();
        if (selImageList != null && selImageList.size() > 0) {
            appPresenter.uploadFiles2(selImageList, ConstantValue.RequestKey.uploadfiles);
        } else {
            dismissProgress();
            ToastUtils.showShortToastSafe("请上传图片");
        }
    }

    @Override
    public void onSuccess(String code, String msg, Object data, String actionType) {
        dismissProgress();
        if (ConstantValue.RequestKey.uploadfiles.equals(actionType)) {
            List<UploadFilesEntity> list = (List<UploadFilesEntity>) data;

            if (list != null && list.size() > 0) {

                Logger.e("xuke", "list=" + list.size());
                StringBuilder stringBuilder = new StringBuilder("");
                for (int i = 0; i < list.size(); i++) {
                    UploadFilesEntity uploadFilesEntity = list.get(i);
                    String url = uploadFilesEntity.getUrl();


                    if (TextUtils.isEmpty(stringBuilder.toString())) {
                        stringBuilder.append(url);
                    } else {
                        stringBuilder.append("," + url);
                    }
                }
                String s = stringBuilder.toString();
                Logger.e("xuke", "s=" + s);
                submitOrder(s);
            }
        }

        if (ConstantValue.RequestKey.new_task_tijiao.equals(actionType)) {
            ToastUtils.showShortToastSafe("提交成功,管理员审核中");
        }
    }

    @Override
    public void onFailed(String code, String msg) {
        dismissProgress();
        ToastUtils.showShortToastSafe(msg);
    }

    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                pickImage();
                break;
            default:
                //打开预览
                Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                break;
        }
    }

    private void pickImage() {
        //打开选择,本次允许选择的数量
        ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
        ImagePicker.getInstance().setCrop(false);
        ImagePicker.getInstance().setShowCamera(true);
        ImagePicker.getInstance().setMultiMode(true);
        Intent intent1 = new Intent(context, ImageGridActivity.class);
        startActivityForResult(intent1, REQUEST_CODE_SELECT);
    }

    @SuppressWarnings("unchecked")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    selImageList.addAll(images);
                    adapter.setImages(selImageList);
                }
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (images != null) {
                    selImageList.clear();
                    selImageList.addAll(images);
                    adapter.setImages(selImageList);
                }
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
